package araxy.blog.security.shiro;

import araxy.blog.entity.User;
import araxy.blog.mapper.UserMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;


public class MyRealm extends AuthorizingRealm {

    @Resource
    private UserMapper userMapper;

    //认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        String username = usernamePasswordToken.getUsername();
        User user = new User();
        user.setUsername(username);
        User ret = userMapper.selectByUserConditions(user);
        if(ret == null) {
            throw new UnknownAccountException("账号或密码不正确");
        }
        return new SimpleAuthenticationInfo(username,ret.getPassword(),getName());
    }

    //授权方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取账号
        String username = (String) principalCollection.getPrimaryPrincipal();
        User user = userMapper.selectByUsername(username);
        Set<String> roles = new HashSet<>();
        if (user.getAdminFlag()) {
            roles.add("admin");
        }
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addRoles(roles);
        return authorizationInfo;
    }
}
